package handlers

import (
	"net/http"
	"ota-backend/config"
	"ota-backend/models"
	"time"

	"github.com/gin-gonic/gin"
)

// DeviceHandler 设备处理器
type DeviceHandler struct{}

// NewDeviceHandler 创建设备处理器
func NewDeviceHandler() *DeviceHandler {
	return &DeviceHandler{}
}

// CreateDevice 创建设备
func (h *DeviceHandler) CreateDevice(c *gin.Context) {
	var device models.Device
	if err := c.ShouldBindJSON(&device); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查产品是否存在
	var product models.Product
	if err := config.DB.First(&product, "id = ?", device.ProductID).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "产品不存在"})
		return
	}

	// 检查SN是否已存在
	var existingDevice models.Device
	if err := config.DB.Where("sn = ?", device.SN).First(&existingDevice).Error; err == nil {
		c.JSON(http.StatusConflict, gin.H{"error": "设备SN已存在"})
		return
	}

	// 设置默认状态为offline
	device.Status = "offline"
	device.LastCheckTime = time.Now()

	if err := config.DB.Create(&device).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, device)
}

// GetDevices 获取设备列表
func (h *DeviceHandler) GetDevices(c *gin.Context) {
	productID := c.Query("product_id")
	status := c.Query("status")

	var devices []models.Device
	query := config.DB.Preload("Product")

	if productID != "" {
		query = query.Where("product_id = ?", productID)
	}

	if status != "" {
		query = query.Where("status = ?", status)
	}

	if err := query.Order("last_check_time DESC").Find(&devices).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, devices)
}

// GetDevice 获取单个设备
func (h *DeviceHandler) GetDevice(c *gin.Context) {
	id := c.Param("id")

	var device models.Device
	if err := config.DB.Preload("Product").First(&device, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "设备不存在"})
		return
	}

	c.JSON(http.StatusOK, device)
}

// UpdateDevice 更新设备
func (h *DeviceHandler) UpdateDevice(c *gin.Context) {
	id := c.Param("id")

	var device models.Device
	if err := config.DB.First(&device, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "设备不存在"})
		return
	}

	var updateData models.Device
	if err := c.ShouldBindJSON(&updateData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 如果更新了SN，检查是否与其他设备冲突
	if updateData.SN != "" && updateData.SN != device.SN {
		var existingDevice models.Device
		if err := config.DB.Where("sn = ? AND id != ?", updateData.SN, id).First(&existingDevice).Error; err == nil {
			c.JSON(http.StatusConflict, gin.H{"error": "设备SN已存在"})
			return
		}
	}

	// 如果更新了产品ID，检查产品是否存在
	if updateData.ProductID != "" && updateData.ProductID != device.ProductID {
		var product models.Product
		if err := config.DB.First(&product, "id = ?", updateData.ProductID).Error; err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "产品不存在"})
			return
		}
	}

	if err := config.DB.Model(&device).Updates(updateData).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, device)
}

// DeleteDevice 删除设备
func (h *DeviceHandler) DeleteDevice(c *gin.Context) {
	id := c.Param("id")

	var device models.Device
	if err := config.DB.First(&device, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "设备不存在"})
		return
	}

	if err := config.DB.Delete(&device).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "设备删除成功"})
}

// UpdateDeviceStatus 更新设备状态（用于设备心跳）
func (h *DeviceHandler) UpdateDeviceStatus(c *gin.Context) {
	sn := c.Param("sn")

	var device models.Device
	if err := config.DB.Where("sn = ?", sn).First(&device).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "设备不存在"})
		return
	}

	device.LastCheckTime = time.Now()
	device.Status = "online"

	if err := config.DB.Save(&device).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "设备状态更新成功"})
}

// DeviceQuery 终端查询接口（如果设备不存在则自动创建）
func (h *DeviceHandler) DeviceQuery(c *gin.Context) {
	sn := c.Query("sn")
	productID := c.Query("product_id")
	currentVersion := c.Query("current_version")

	if sn == "" || productID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "sn和product_id为必填参数"})
		return
	}

	// 检查产品是否存在
	var product models.Product
	if err := config.DB.First(&product, "id = ?", productID).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "产品不存在"})
		return
	}

	// 查找设备
	var device models.Device
	err := config.DB.Where("sn = ?", sn).First(&device).Error

	if err != nil {
		// 设备不存在，自动创建
		device = models.Device{
			SN:             sn,
			ProductID:      productID,
			CurrentVersion: currentVersion,
			Status:         "online",
			LastCheckTime:  time.Now(),
		}

		if err := config.DB.Create(&device).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "设备创建失败"})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"message": "设备已自动创建",
			"device":  device,
		})
	} else {
		// 设备存在，更新状态和最后检查时间
		device.Status = "online"
		device.LastCheckTime = time.Now()

		// 如果提供了当前版本，则更新
		if currentVersion != "" {
			device.CurrentVersion = currentVersion
		}

		if err := config.DB.Save(&device).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "设备状态更新失败"})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"message": "设备状态已更新",
			"device":  device,
		})
	}
}
